//构建request基类

import {Config} from '../utils/config.js';
import {Token} from 'token.js';

class Base{

  constructor(){
    this.baseRequestUrl = Config.restUrl;
  }

  //request基类
  //当noRefech为true时，不做未授权重试机制
  request(params, noRefech){
    var that = this;
    var url = this.baseRequestUrl + params.url;

    if(!params.type){
      params.type = 'GET';
    }
    
    wx.request({
      url: url,
      data: params.data,
      method: params.type,
      header: {
        'content_type': 'application/json',
        'token': wx.getStorageSync('token'),
      },
      success:function(res){
        //对返回结果的状态码进行判断，从而重新获取token令牌
        var code = res.statusCode.toString();
        var startChar = code.charAt(0);

        if(startChar == '2'){
          params.successCallback && params.successCallback(res.data);
        }else{
          if( code == '401' ){
            if(!noRefech){
              that._refech(params);
            }
          }
          if (noRefech) {
            params.errorCallback && params.errorCallback(res.data);
          }
        }
        
      },
      fail:function(res){
        console.log(res);
      }
    })
  }

  //获取令牌后，再次向原来的url发送请求
  _refech(params){
    var token = new Token();
    token.getTokenFromServer((token) => {
      this.request(params, true);
    });
  }

  // 获取event元素上绑定的值
  getDataSet(event,key){
    return event.currentTarget.dataset[key];
  }

}

export {Base};